<script setup>
import {Permission} from '@/utils/resource'
import {confirm} from '@/utils/element-helper'
import {permissionStore} from "@/store/perminnion";
import {nextTick, ref} from "vue";
import {useRouter} from "vue-router";

const permissionStoreS = permissionStore()
const loading = ref(false)
const router = useRouter()

loadTree()

async function loadTree() {
  loading.value = true
  await permissionStoreS.loadPermissions()
  await nextTick()
  loading.value = false
}

function handleAdd() {
  router.push({path: "/permission/new"})
}

function handleEdit(index, row, id) {
  router.push({path: "/permission/" + row.id})
}

function handleChild(index, row, parent) {
  router.push({path: "/permission/new/" + row.id})
}

function handleDelete(index, row, id) {
  confirm({_content: "删除权限将一并删除所有子权限, 是否继续?"}, () => Permission.del(row.id), (resp) => loadTree())
}


</script>

<template>
  <el-form :inline="true">
    <el-form-item style="float: right">
      <el-button type="success" @click="handleAdd" icon="CirclePlus" plain>新增</el-button>
    </el-form-item>
  </el-form>
  <el-table
      :data="permissionStoreS.permissionsTree"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      v-loading="loading"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
    <el-table-column
        prop="name"
        label="名称">
      <template #default="scope">
        <el-icon style="margin-right: 5px;">
          <component :is="scope.row.icon"></component>
        </el-icon>{{ scope.row.name }}
      </template>
    </el-table-column>
    <el-table-column
        prop="code"
        label="编码">
    </el-table-column>
    <el-table-column
        prop="priority"
        label="排序"
        width="70">
    </el-table-column>
    <el-table-column
        prop="type"
        label="类型"
        width="100">
      <template #default="scope">
        {{ scope.row.type === 0 ? "页面权限" : "接口权限" }}
      </template>
    </el-table-column>
    <el-table-column label="操作" width="300" align="center">
      <template #default="scope">
        <el-button
            type="warning"
            size="small"
            @click="handleEdit(scope.$index, scope.row, scope.row.id)">编辑
        </el-button>
        <el-button v-if="scope.row.type===0"
                   type="success"
                   size="small"
                   icon="Plus"
                   @click="handleChild(scope.$index, scope.row,scope.row.parent)">添加子权限</el-button>
        <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.$index, scope.row, scope.row.id)">删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>


<style scoped>


</style>
